<template>
  <div class="flex-container">
    <div class="map-container">
      <img 
        :src="mapSrc"
        class="map-image"
        alt="Campus Map"
        @click="handleClick"
      />
      <div 
        v-for="(point, index) in points" 
        :key="index"
        class="marker"
        :style="{ left: point.x + 'px', top: point.y + 'px' }"
      ></div>
      <div v-for="facility in facilities" :key="facility.id" class="facility" :style="getFacilityStyle(facility)">
        <div class="facility-name">{{ facility.name }}</div>
      </div>
    </div>
    
    <div class="card-container">
      <h2 style="color: cornflowerblue;">{{ facility.name }}</h2>
      
      <div class="info-columns">
        <StoresList :storesList="storesList" />
        <EventsList :eventsList="eventsList" />
        <ActivitiesList :activitiesList="activitiesList" />
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted,reactive } from 'vue';
import mapImage from '@/assets/images/cduNew.png'; // 使用 import 引入图片
import { listFacilities, addFacility, updateFacility, deleteFacility } from "@/api/pages/facility";
import StoresList from './components/StoresList.vue';
import EventsList from './components/EventsList.vue';
import ActivitiesList from './components/ActivitiesList.vue';
//根据商店id获取当前商店的服务和商品
import { getGoodsListByStoreId}  from "@/api/pages/product";
//根据设施id获取当前设施的事件
 import { getEventByFacilityId}  from "@/api/pages/event";
//根据设施id获取当前设施的活动
 import { getActivitiesByFacilityId}  from "@/api/pages/activity";
//根据设施id获取当前设施的商店
 import { getStoresByFacilityId}  from "@/api/pages/virtualStore";


// 使用 ref 定义响应式数据
const mapSrc = mapImage;
const points = ref([]); // 存储点击的相对坐标
const imageWidth = ref(0);
const imageHeight = ref(0);
const loading = ref(false);
const facilities=ref([]); // 设施列表
const facilityTitle = ref(""); // 设施名称
const goodsList = ref([]); // Store goods and services
const eventsList = ref([]); // Store events
const activitiesList = ref([]); // Store activities
const storesList = ref([]); // Store stores
const facility=ref({}); // 当前点击的设施
const queryParams = reactive({
    name: "",
    type: undefined,
  });
  // 查询设施列表
  const getList = () => {
    loading.value = true;
    listFacilities(queryParams).then(response => {
      facilities.value = response.data;
      loading.value = false;
    });
  };
  

// 设施数据

const clickPoints = ref([]); // 存储所有点击的坐标
const groupedPoints = ref([]); // 存储每四个点击的坐标组

const handleClick = (event) => {
  //打印照片宽高
  console.log(`Image width: ${imageWidth.value}, height: ${imageHeight.value}`);
  // const x = (event.offsetX / imageWidth.value) * 800; // 计算相对位置
  // const y = (event.offsetY / imageHeight.value) * 600; // 计算相对位置
  const x = event.offsetX 
  const y = event.offsetY 
  console.log(`x,y: (${x}, ${y})`);
  console.log(`event.offsetX: ,event.offsetY: (${event.offsetX}, ${event.offsetY})`);

  // 存储点击的点
  points.value.push({ x: event.offsetX, y: event.offsetY });

  // 检查点击位置是否在某个设施内部
  const clickedFacility = facilities.value.find(facility => isInsideFacility(x, y, facility));
  if (clickedFacility) {
    alert(`Clicked on: ${clickedFacility.name}`);
    //打印facility
    console.log("当前设施信息:",clickedFacility);
    //检查是否存在关联的商店id并获取当前商店的服务和商品以及事件
    // if(clickedFacility.storeId!==0){
    //   //TODO: 获取当前商店的服务和商品以及事件
    //   console.log("当前商店的id:",clickedFacility.storeId);
    //   facilityTitle.value = clickedFacility.name;
    //   facility.value = clickedFacility;
    //   getGoodsListByStoreId(clickedFacility.storeId).then(response => {
    //     console.log("当前商店的服务和商品以及事件:",response.data);
    //     goodsList.value = response.data;
    //   }); 
      //打印商品列表
      // console.log("当前商店的商品列表:",response.data);

    //}
    //检查当前位置是否存在事件
    //TODO: 获取当前位置的事件
    getEventByFacilityId(clickedFacility.id).then(response => {
      console.log("当前设施的事件:",response.data);
      eventsList.value = response.data;
    });
    //检查当前位置是否存在活动
    //TODO: 获取当前位置的活动
    getActivitiesByFacilityId(clickedFacility.id).then(response => {
      console.log("当前设施的活动:",response.data);
      activitiesList.value = response.data;
    });
    //检查当前位置是否存在商店
    //TODO: 获取当前位置的商店
    getStoresByFacilityId(clickedFacility.id).then(response => {
      console.log("当前设施的商店:",response.data);
      storesList.value = response.data;
    });





  } else {
    console.log(`Clicked at coordinates: (${x}, ${y})`);
  }
     // 存储每次点击的坐标
     clickPoints.value.push({ x, y });

// 每四次点击组合一个坐标组
if (clickPoints.value.length % 4 === 0) {
  const points = clickPoints.value.slice(-4); // 获取最近的四个点
  const formattedPoints = formatPoints(points);
  groupedPoints.value.push(formattedPoints); // 存储格式化的坐标组
  console.log(`Stored points group:`, formattedPoints);
}
    
  
};



const formatPoints = (points) => {
  return points.map(point => `(${point.x}, ${point.y})`);
};

// 检查点击位置是否在设施的矩形区域内
const isInsideFacility = (x, y, facility) => {
  const coordinates = parseLocation(facility.location);
  const [topLeft, topRight, bottomRight, bottomLeft] = coordinates;

  // 确定矩形的边界
  const minX = Math.min(topLeft[0], bottomLeft[0]);
  const maxX = Math.max(topRight[0], bottomRight[0]);
  const minY = Math.min(topLeft[1], topRight[1]);
  const maxY = Math.max(bottomLeft[1], bottomRight[1]);

  return x >= minX && x <= maxX && y >= minY && y <= maxY;
};

//解析位置字符串为坐标数组
const parseLocation = (location) => {
    // 去掉字符串中的空格、单引号和双引号
  location = location.replace(/['"\s]+/g, '');

    // 将方括号转换为圆括号
    location = location.replace(/\[/g, '(').replace(/\]/g, ')');

  const matches = location.match(/\((\d+),(\d+)\)/g);
  return matches.map(match => match.replace(/[()]/g, '').split(',').map(Number));
};

// 根据设施的坐标计算样式
// const getFacilityStyle = (facility) => {
//   const coordinates = parseLocation(facility.location);
//   const [topLeft, topRight, bottomRight, bottomLeft] = coordinates;
  
//   const width = topRight[0] - topLeft[0]; // 宽度
//   const height = bottomLeft[1] - topLeft[1]; // 高度
  
//   return {
//     position: 'absolute',
//     left: topLeft[0] + 'px',
//     top: topLeft[1] + 'px',
//     width: width + 'px',
//     height: height + 'px',
//     backgroundColor: 'rgba(255, 0, 0, 0.3)', // 半透明背景
//     border: '1px solid red', // 红色边框
//     borderRadius: '4px'
//   };
// };
const getFacilityStyle = (facility) => {
  const coordinates = parseLocation(facility.location);
  if (!coordinates) {
    console.warn(`Invalid location for facility: ${facility.name}`);
    return {}; // 返回空样式以避免错误
  }

  // 获取多边形的边界
  const left = Math.min(...coordinates.map(coord => coord[0]));
  const top = Math.min(...coordinates.map(coord => coord[1]));
  const right = Math.max(...coordinates.map(coord => coord[0]));
  const bottom = Math.max(...coordinates.map(coord => coord[1]));

  // 计算多边形的宽度和高度
  const width = right - left;
  const height = bottom - top;

  // 使用 clipPath 定义多边形
  const polygonPoints = coordinates.map(coord => {
    return `${(coord[0] - left) / width * 100}% ${(coord[1] - top) / height * 100}%`;
  }).join(', ');

  return {
    position: 'absolute',
    left: left + 'px',
    top: top + 'px',
    width: width + 'px',
    height: height + 'px',
    backgroundColor: 'rgba(255, 0, 0, 0.3)', // 半透明背景
    border: '1px solid red', // 红色边框
    borderRadius: '1px',
    clipPath: `polygon(${polygonPoints})` // 使用 clipPath 定义多边形
  };
};
  

// 获取图片尺寸
const setImageDimensions = () => {
  const img = new Image();
  img.src = mapSrc;
  img.onload = () => {
    imageWidth.value = img.width;
    imageHeight.value = img.height;
  };
};

// 在组件挂载时获取图片尺寸
onMounted(() => {
  setImageDimensions();
});
  
  // 初始化设施列表
  getList();
</script>
<style>
.flex-container {
  display: flex; /* Use flexbox for layout */
  min-width: 1200px; /* Set minimum width */
  max-width: 1600px;
  align-items: flex-start; /* Align items at the start */
  flex-direction: column; /* Stack items vertically */
}

.map-container {
  position: relative;
  width: 1200px; /* 根据图片宽度自适应 */
  height: auto; /* 根据图片高度自适应 */
}

.map-image {
  display: block; /* 确保图片是块级元素 */
  width: 1077px; /* 适应容器宽度 */
  max-height: 100%; /* 适应容器 */
}

.marker {
  position: absolute;
  width: 20px;
  height: 20px;
  background-color: red;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

.facility {
  position: absolute;
  pointer-events: none; /* Disable pointer events for facilities */
}

.facility-name {
  color: white;
  font-weight: bold;
  font-size: 15px;
  text-align: center;
  margin-top: 5px;
}

.card-container {
  margin-top: 20px; /* 地图与卡片容器之间的间距 */
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 10px;
  flex-grow: 1; /* 使卡片容器占据剩余空间 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.info-columns {
  display: flex; /* 使用 flexbox 布局 */
  justify-content: space-between; /* 分散排列 */
}

.info-column {
  flex: 1; /* 每列占相等宽度 */
  margin: 0 10px; /* 列间距 */
}

.stores-list, .events-list, .activities-list {
  max-height: 800px; /* 设置最大高度 */
  overflow-y: auto; /* 纵向滚动条 */
  margin-bottom: 15px; /* 每个部分之间的间距 */
}

.card {
  margin-bottom: 10px;
  padding: 10px;
  border: 2px solid #eee;
  border-radius: 4px;
}

.card h4 {
  margin: 0;
}

.card p {
  margin: 5px 0 0;
}
</style>